package com.sunfeng.heima.chap1;



import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadStateTest {
    public static void main(String[] args) throws InterruptedException {

        Object lock = new Object();

        // 线程状态
        // 初始状态   可运行状态    休眠状态  可运行状态    终止状态
        //Java 线程状态
        // new     runnable(ready running)   block  waiting  ( timed waiting) terminated


        //  下面四种情况会是线程进入 waiting 状态
        new Thread(()->{
            synchronized (lock){
                try {
                    System.out.println("Object wait");
                    lock.wait();
                    System.out.println("Object notify");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

       new Thread(()->{
           try {
               TimeUnit.SECONDS.sleep(2);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           synchronized (lock){
               //  下面四种情况会使线程  waiting 状态 -> runnable
               lock.notifyAll();
           }

       }).start();

        Thread thread = new Thread(()->{
            System.out.println("join 线程开始启动");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        // 等待线程执行完毕
        thread.join();
        System.out.println("join 结束");

        Thread parkThread = new Thread(() -> {
            System.out.println("线程开始进入park状态");
            LockSupport.park();
            System.out.println("线程结束park");
        });
        parkThread.start();


        TimeUnit.SECONDS.sleep(2);
        LockSupport.unpark(parkThread);


        ReentrantLock reentrantLock = new ReentrantLock();
        reentrantLock.lock();

        reentrantLock.unlock();

        /**
         *  block   线程通过synchronize 关键字 等待锁的状态
         */
    }
}
